package com.ctg.behavior.calc.controller.retentions;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.common.CtgResult;
import com.ctg.behavior.common.retentions.CtRetentionsCalcRequest;
import com.ctg.behavior.common.retentions.CtRetentionsCalcResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/retentions")
public class RetentionsController {

    @Value("${simulator.path}")
    private String simlutorPath;

    @PostMapping("/report")
    public CtRetentionsCalcResult report(@RequestBody CtRetentionsCalcRequest request) throws Exception {

        CtRetentionsCalcResult result = new CtRetentionsCalcResult();
        log.info("request", JSON.toJSONString(request));

        String filePath = simlutorPath + "/retentions/report/";
        FileUtils.forceMkdir(new File(filePath));

        String targetName = this.builderTargetFileName(filePath, request);
        String targetFilePath = filePath + targetName;
        // 检查文件并读取文件
        File targetFile = new File(targetFilePath);
        if (!targetFile.exists()) {
            ClassPathResource classPathResource = null;
            if (request.getReq().getByFields().size() != 0) {
                if (request.getReq().getUnit().equals("week")) {
                    classPathResource = new ClassPathResource("retentions/report/retentions.groupby_week.json");
                } else if (request.getReq().getUnit().equals("month")) {
                    classPathResource = new ClassPathResource("retentions/report/retentions.groupby_month.json");
                } else {
                    classPathResource = new ClassPathResource("retentions/report/retentions.groupby.json");
                }
            } else {
                if (request.getReq().getUnit().equals("week")) {
                    classPathResource = new ClassPathResource("retentions/report/retentions.simple_week.json");
                } else if (request.getReq().getUnit().equals("month")) {
                    classPathResource = new ClassPathResource("retentions/report/retentions.simple_month.json");
                } else if (request.getReq().getMeasures().get(0).getEventId().equals("_AppClick")) {
                    log.info("request ===> retention.simple_click.json");
                    classPathResource = new ClassPathResource("retentions/report/retentions.simple_click.json");
                } else {
                    classPathResource = new ClassPathResource("retentions/report/retentions.simple.json");
                }
            }

            InputStream inputStream = classPathResource.getInputStream();
            List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
            StringBuilder sbuilder = new StringBuilder();
            for (String line : lines) {
                sbuilder.append(line);
            }
            result = JSON.parseObject(sbuilder.toString(), CtRetentionsCalcResult.class);
        } else {
            String resultText = FileUtils.readFileToString(targetFile, "UTF-8");
            result = JSON.parseObject(resultText.toString(), CtRetentionsCalcResult.class);
        }

        log.info("result", JSON.toJSONString(result));

        return result;
    }

    @PostMapping("/reportTMU")
    public CtgResult report(@RequestBody RetentionsTMUInfo info) throws Exception {
        CtgResult result = new CtgResult();

        String filePath = simlutorPath + "/retentions/report";
        FileUtils.forceMkdir(new File(filePath));

        String targetName = this.builderTargetFileName(filePath, info.getRequest());
        String targetFilePath = filePath + targetName;

        File targetFile = new File(targetFilePath);
        FileUtils.writeStringToFile(targetFile, JSON.toJSONString(info.getResponse()), "UTF-8");

        //result.setMsg("report response body updload successfully!(test mode)");

        return result;
    }

    public String builderTargetFileName(String filePath, CtRetentionsCalcRequest request) {

        // 拼JSON文件名
        if (!request.getReq().getByFields().isEmpty()) {
            return "retentions/report/retentions.groupby.json";
        } else if (!request.getReq().getFirstEvent().getFilter().getConditions().isEmpty()) {
            return "retentions/report/retentions.nogroupby.json";
        } else {
            return "retentions/report/retentions.simple.json";
        }

    }

}
